// @charset "utf-8";

define(function(require, exports, module) {
	var publicMethod = require('../../public/public');
	var clientApi = require('../../public/clientapi');

	function IndexBase() {

	}
	IndexBase.prototype = {
		formatData: function(rst, code, type) {
			var result = JSON.parse(rst);
			var codeArr = code.split(',');
			var dataObj = {};
			$.each(codeArr, function(i, n) {
				var arr = [];
				$.each(result[n], function(j, val) {
					arr.push(parseFloat(val[type]));
				})
				dataObj[n] = arr;
			});
			return dataObj;
		},
		formatDataSection: function(rst, code, type) {
			var result = JSON.parse(rst);
			var codeArr = code.split(',');
			var dataObj = {};
			var dateArr = [];
			$.each(codeArr, function(i, n) {
				var arr = [];
				if (n != '1A0001') {
					$.each(result[n], function(j, val) {
						arr.push(parseFloat(val[type]));
						var date = clientApi.timeStamp(j * 1000, '-');
						dateArr.push(date.substr(5));
					})
				} else {
					$.each(result[n], function(j, val) {
						arr.push(parseFloat(val[type]));
					})
				}
				dataObj[n] = arr;
			});
			dataObj['dateArr'] = dateArr;
			return dataObj;
		},
		requestDay: function(code, begin, end, callback) {
			var self = this;
			var getData = async function(param) {
				var type = '3672520';
				var rst = await clientApi.thsQuote.getData2({
					type: type,
					code: code,
					period: 'day',
					mode: 'after',
					time: {
						begin: begin,
						end: end
					},
					updateMode: 1,
					timeStamp: 1
				});
				var rstData = self.formatDataSection(rst, code, type);
				callback(rstData);
			};
			clientApi.thsQuote.request({
				type: '11,6',
				code: code,
				period: 'day',
				begin: begin,
				end: end,
				onready: getData
			});
		},
		requestMin: function(code, date, callback) {
			var self = this;
			var rst;
			var getData = async function(param) {
				var type = '2525646';
				rst = await clientApi.thsQuote.getData2({
					type: type,
					code: code,
					period: 'min',
					time: {
						begin: date,
						end: date,
						timeFmt: 1
					},
					updateMode: 1,
					timeStamp: 1
				});
				var rstData = self.formatData(rst, code, type);
				callback(rstData);
			};
			clientApi.thsQuote.request({
				type: '10,6',
				code: code,
				period: 'min',
				begin: date,
				end: date,
				timeFmt: 1,
				onready: getData
			});
		},
		requestZxData: async function(type, date) {
			var self = this;
			var tradeDay = await clientApi.getTradingDay();
			if (date == tradeDay) {
				var url = 'zx/get_homepage_data.lua?op=' + type + '&begin_date=' + date + '&end_date=' + date;
				var bool = clientApi.thsQuote.requestZxData({
					url: url,
					onready: function(res) {
						if (res == '[]') {
							self.renderRisingProb(type, '');
						} else {
							res = JSON.parse(res);
							self.renderRisingProb(type, res[0]['data']);
						}
					}
				});
				if (!bool) {
					self.renderRisingProb(type, '');
				}
			} else {
				self.requestHisZxData(type, date);
			}
		},
		pjhcId: {
			'qrpjhc': 11,
			'zdtjpjhc': 12,
			'zqxypjhc': 17,
			'hsgtzjlxpjhc': 18,
			'rzrqpjhc': 20,
			'zjlrqspjhc': 21,
			'zjbypjhc': 19,
			'zrhsqspjhc': 26,
			'zrgzfpjhc': 25,
			'zrzxpjhc': 27,
			'sgtcjqspjhc': 29,
			'hgtcjqspjhc': 30,
			'zrrmpjhc': 28
		},
		requestNewZxData: async function (type, date) {
			var self = this;
			var tradeDay = await clientApi.getTradingDay();
			if (date == tradeDay) {
				var bool = clientApi.thsQuote.requestZxData({
					url: 'zx/freeclient/homepage/'+ type +'.json',
					onready: function(result) {
						if (result == '[]') {
							self.renderRisingProb(type, '');
						} else {
							result = JSON.parse(result);
							self.renderRisingProb(type, result['data']);
						}
					}
				});
				if (!bool) {
					self.renderRisingProb(type, '');
				}
			} else {
				self.requestHisZxData(type, date);
			}
		},
		requestHisZxData: function (type, date) {
			var self = this;
			publicMethod.ajaxJson({
				url: publicMethod.urlList.pjhcUrl,
				data: {
					date: date,
					'config_id': self.pjhcId[type]
				},
				callback: function(result) {
					if (result && result.errorcode === 0) {
						result = result['result']['data'];
						self.renderRisingProb(type, result);
					} else {
						self.renderRisingProb(type, '');
					}
				}
			});
		},
		renderRisingProb: function(type, res) {
			var $hcData = $('#' + type + 'HcData');
			if (res == '') {
				$hcData.text('历史数据回测中...');
			} else {
				var hcText = '<a href="' + res.url + '" class="hc-link"><span>' + res.detail + '</span><i class="details">查看详情&gt;</i></a>';
				$hcData.html(hcText);
			}
		},

		datePicker: async function(date, domId, callback, callbackI, minDate) {
			var self = this;
			var $datePicker = $('#' + domId + 'DatePicker');
			self.originalDateStr = publicMethod.dateSplit(date);
			$datePicker.val(self.originalDateStr);


			$datePicker.on('click', function() {
				WdatePicker({
					skin: 'blackbyjsc',
					readOnly: true,
					isShowClear: false,
					isShowToday: true,
					isShowOK: true,
					qsEnabled: false,
					dateFmt: 'yyyy-MM-dd',
					minDate: minDate,
					maxDate: '%y-%M-%d',
					disabledDays: [0, 6],
					onpicked: async function(dp) {
						var _newDate = dp.cal.getNewDateStr();
						var newDate = parseInt(_newDate.replace(/-/g, ''));

						var today = await clientApi.serverTime();
						var tradeDay = await clientApi.getTradingDay(newDate);
						if (tradeDay != newDate && newDate != today) {
							$datePicker.val(self.originalDateStr);
							$('#' + domId + 'NonTradeTip').fadeIn(100);
							setTimeout(function() {
								$('#' + domId + 'NonTradeTip').fadeOut(800);
							}, 1200);

						} else {
							self.originalDateStr = _newDate;
							callback(newDate);
						}
						$datePicker.blur();
					}
				});
			})

			var preMonthDate = await clientApi.preMonthDate(),
				tradingDay = await clientApi.getTradingDay(),
				_preMonthDate = publicMethod.dateSplit(preMonthDate),
				_tradingDay = publicMethod.dateSplit(tradingDay);
			var $sDatePicker = $('#' + self.domId + 'SDatePicker'),
				$eDatePicker = $('#' + self.domId + 'EDatePicker');

			var startDate = preMonthDate,
				endDate = tradingDay;
			$('#' + self.domId + 'IntervalBtn').on('click', function() {
				self.type = 'day';
				$(this).parent('.date-wrap-single').hide();
				$(this).parent('.date-wrap-single').next('.date-wrap-interval').show();

				$sDatePicker.val(_preMonthDate);
				$eDatePicker.val(_tradingDay);
				callbackI(startDate, endDate);
			});
			$('#' + self.domId + 'SingleBtn').on('click', function() {
				self.type = 'min';
				$(this).parent('.date-wrap-interval').hide();
				$(this).parent('.date-wrap-interval').prev('.date-wrap-single').show();

				$datePicker.val(_tradingDay);
				callback(tradingDay);
			});


			var startEl = domId + 'SDatePicker',
				endEl = domId + 'EDatePicker';
			$sDatePicker.on('click', function() {
				WdatePicker({
					skin: 'blackbyjsc',
					el: startEl,
					readOnly: true,
					isShowClear: false,
					isShowToday: true,
					isShowOK: true,
					qsEnabled: false,
					dateFmt: 'yyyy-MM-dd',
					minDate: minDate,
					maxDate: '#F{$dp.$D(\'' + endEl + '\', {d: -1})}',
					disabledDays: [0, 6],
					onpicked: function(dp) {
						startDate = parseInt((dp.cal.getNewDateStr()).replace(/-/g, ''));

						callbackI(startDate, endDate);
						$sDatePicker.blur();
					}
				});
			});
			$eDatePicker.on('click', function() {
				WdatePicker({
					skin: 'blackbyjsc',
					el: endEl,
					readOnly: true,
					isShowClear: false,
					isShowToday: true,
					isShowOK: true,
					qsEnabled: false,
					dateFmt: 'yyyy-MM-dd',
					minDate: '#F{$dp.$D(\'' + startEl + '\', {d: -1})}',
					maxDate: '%y-%M-%d',
					disabledDays: [0, 6],
					onpicked: function(dp) {
						endDate = parseInt((dp.cal.getNewDateStr()).replace(/-/g, ''));

						callbackI(startDate, endDate);
						$eDatePicker.blur();
					}
				});
			});
		},

		renderChart: function (params) {
			var self = this;
			var indexName = params.indexName,
				series1 = params.series1,
				series2 = params.series2,
				latestVal1 = params.latestVal1,
				latestVal2 = params.latestVal2,
				dateArr = params.dateArr;


			var _tickPositions = [0, 120, 241],
				_tickInterval = '120',
				_xAxisMin = '0',
				_xAxisMax = '241',
				_xAxisData = publicMethod.xAxisData;
			if (dateArr) {
				_tickPositions = null;
				_tickInterval = Math.ceil(dateArr.length / 10);
				_xAxisMin = null,
				_xAxisMax = null,
				_xAxisData = dateArr;
			}
			var chartOptions = {
				credits: {
					enabled: false
				},
				title: {
					text: ''
				},
				chart: {
					backgroundColor: null,
					style: {
						"fontFamily": "Arial, \"Microsoft yahei\", Verdana, Helvetica, sans-serif",
						"fontSize": "12px"
					},
					marginTop: 40,
					marginLeft: 40,
					marginBottom: 30
				},
				series: [{
					name: indexName,
					type: 'line',
					color: '#ff3232',
					lineWidth: 1,
					marker: {
						enabled: false,
						states: {
							hover: {
								fillColor: '#ff3232',
								radius: 2,
								lineColor: 'rgba(255, 255, 255, 1)',
								lineWidthPlus: 1
							}
						}
					},
					data: series1
				}, {
					name: '上证',
					type: 'line',
					color: '#efefef',
					lineWidth: 1,
					marker: {
						enabled: false,
						states: {
							hover: {
								fillColor: '#efefef',
								radius: 2,
								lineColor: 'rgba(200, 200, 200, 1)',
								lineWidthPlus: 1
							}
						}
					},
					data: series2
				}],
				plotOptions: {
					series: {
						stickyTracking: false,
						events: {
							legendItemClick: function() {
								if (this.name !== '上证') {
									clientApi.thsQuote.switchCode(self.indexCode);
									return false;
								}
							}
						}
					},
					line: {
						states: {
							hover: {
								lineWidthPlus: 0
							}
						}
					}
				},
				xAxis: {
					lineWidth: 1,
					tickLength: 4,
					lineColor: '#808080',
					tickColor: '#808080',
					tickInterval: _tickInterval,
					tickPositions: _tickPositions,
					title: {
						text: ''
					},
					categories: _xAxisData,
					gridLineWidth: 0,
					labels: {
						align: 'center',
						rotation: 0,
						style: {
							color: '#afafaf'
						}
					},
					min: _xAxisMin,
					max: _xAxisMax
				},
				yAxis: {
					allowDecimals: false,
					lineWidth: 1,
					tickColor: '#808080',
					tickPosition: 'outside',
					gridLineWidth: 0,
					tickLength: 4,
					tickWidth: 1,
					title: {
						text: ''
					},
					lineColor: '#808080',
					labels: {
						format: '{value}%',
						style: {
							color: '#afafaf'
						},
						x: -7
					}
				},
				legend: {
					align: 'right',
					verticalAlign: 'top',
					floating: false,
					symbolHeight: 10,
					symbolWidth: 14,
					itemStyle: {
						color: '#dedede',
						fontFamily: 'Microsoft yahei',
						fontWeight: 'normal'
					},
					itemHiddenStyle: {},
					itemHoverStyle: {
						color: '#bbb'
					},
					useHTML: true,
					labelFormatter: function() {
						if (this.name === '上证') {
							return '<span class="legend-item">上证 <i class="shLegendData">' + latestVal2 + '</i></span>';
						} else {
							return '<span class="legend-item textline">' + this.name + ' <i class="' + self.domId + 'LegendData">' + latestVal1 + '</i></span>';
						}
					}
				},
				tooltip: {
					shared: true,
					backgroundColor: '#2e3339',
					borderColor: '#505458',
					shape: '',
					crosshairs: [{
						width: 1,
						color: '#afafaf'
					}],
					valueDecimals: 2,
					valueSuffix: '%',
					style: {
						fontFamily: 'Microsoft yahei',
						color: '#fff'
					}
				}
			};

			$('#'+ self.domId +'ChartBox').highcharts(chartOptions);
			self.HighchartsObj = $('#'+ self.domId +'ChartBox').highcharts();
		}
	}

	module.exports = IndexBase;
});